var url = "https://seejoke.com/wechatapi/verificationUser";
function Login(code, username) {
  var that = this
  wx.request({
    url: url,
    data: {
      code: code,
      username: username,
      sign:getApp().data.sign
    },
    success: function (b) {
      //console.log(b);
      // 成功返回用户的唯一ID(这是数据库ID)
      console.log(b.data)
      //wx.setStorageSync('uid', b.data.openId)
    }
  })
}
App({
  data: {
    sign: 'https://seejoke.com'
  },
  onLaunch: function () {
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        Login(res.code, '');
      }
    });
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo;
              typeof cb == "function" && cb(that.globalData.userInfo);
              var username = res.userInfo.nickName;
              var img = res.userInfo.avatarUrl;
              var code = res.code;
              //请求自己的服务器
              Login(code, username);
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res);
              }
            }
          })
        }
      }
    })
  },
  getUserInfo: function (cb) {
    var that = this
    if (this.globalData.userInfo) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    } else {
      //调用登录接口
      wx.login({//login流程
        success: function (res) {//登录成功
          if (res.code) {
            var code = res.code;
            wx.getUserInfo({
              //getUserInfo流程
              success: function (res2) {
                // console.log(res2)
                that.globalData.userInfo = res2.userInfo
                typeof cb == "function" && cb(that.globalData.userInfo)
                var username = res2.userInfo.nickName
                var img = res2.userInfo.avatarUrl
                //请求自己的服务器
                Login(code, username);
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: '获取用户登录态失败！' + res.errMsg
            })
          }
        }
      })
    }
  },
  globalData: {
    userInfo: null
  }
})